package cn.com.pansky.comm.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class CorsFilter implements Filter {

	@Override
	public void destroy() {

	}

	@Override
	public void doFilter(ServletRequest req, ServletResponse res,
			FilterChain chain) throws IOException, ServletException {
		// CORS
		HttpServletRequest request = (HttpServletRequest) req;
		HttpServletResponse response = (HttpServletResponse) res;
		response.addHeader("Access-Control-Allow-Credentials", "true");
		String referer = request.getHeader("Referer");
		if (referer != null) {
			int index = referer.indexOf("/", 8);
			if (index != -1) {
				referer = referer.substring(0, index);
			}
		} else {
			referer = "*";
		}
		response.addHeader("Access-Control-Allow-Origin", referer);
		response.addHeader("Access-Control-Allow-Headers",
				"X-Requested-With,X_Requested_With");
		chain.doFilter(request, response);
	}

	@Override
	public void init(FilterConfig config) throws ServletException {

	}

}
